package db

import (
	"gitee.com/godY/daminghu-cli/cfg"
	"gitee.com/godY/daminghu-cli/common"
	"github.com/astaxie/beego"
	_ "github.com/go-sql-driver/mysql"
	"gitee.com/godY/xormplusy/core"
	"gitee.com/godY/xormplusy/xorm"
	"gitee.com/godY/daminghu-cli/handler"
)

const (
	MaxOpenConns = 20
)

var (
	DBTYPE = make(map[string]string)
	//MySqlConnStr = cfg.Cfg.DBUsername + ":" + cfg.Cfg.DBPassword + "@tcp(" + cfg.Cfg.DBIp + ":" + cfg.Cfg.DBPort + ")/" + cfg.Cfg.DBSchema + cfg.Cfg.DBConnParam
)

func init() {
	DBTYPE["VARCHAR"] = "string"
	DBTYPE["INT"] = "int64"
}

var Engine *xorm.Engine

var Tables []*common.Table

func InitDb() {

	beego.Debug("MySqlConnStr ", cfg.Cfg.GetMySqlConn())

	var err error
	Engine, err = xorm.NewEngine("mysql", cfg.Cfg.GetMySqlConn())
	if err != nil {
		beego.Error(err.Error())
		panic(err)
	}
	//err = Engine.Ping()
	if err != nil {
		beego.Error(err.Error())
		panic(err)
	}
	tbs, err := Engine.DBMetas()
	if err != nil {
		beego.Error(err.Error())
		panic(err)
	}

	initHandlerTables(tbs)
	Engine.SetMaxOpenConns(MaxOpenConns)
}

func initHandlerTables(tbs []*core.Table) {
	for _, t := range tbs {
		tempTable := common.Table{}
		tempTable.Name = t.Name
		tempTable.Comment = handler.ConvertComment(t.Comment)
		tempColumns := make([]*common.Column, 0)
		for _, c := range t.Columns() {
			tempColumn := common.Column{}
			tempColumn.Name = c.Name
			tempColumn.TableName = c.TableName
			tempColumn.FieldName = c.FieldName

			tempColumn.SQLType = common.SQLType{}
			tempColumn.SQLType.Name = c.SQLType.Name
			tempColumn.SQLType.DefaultLength = c.SQLType.DefaultLength
			tempColumn.SQLType.DefaultLength2 = c.SQLType.DefaultLength2

			tempColumn.Comment = handler.ConvertComment(c.Comment)
			tempColumns = append(tempColumns, &tempColumn)
		}
		tempTable.Columns = tempColumns
		Tables = append(Tables, &tempTable)
	}

	//bytes, _ := json.Marshal(demo.CreateReq{Tables: Tables})
	//ioutil.WriteFile(cfg.Cfg.ServerDistPath+"data.json", bytes, os.ModePerm)
}
